<?php
/**
 * @package pmapi
 * @copyright Copyright (c)2014 Enrico Fagnoni
 * @license GNU General Public License version 3, or later
 *
 * @since 1.0.0
 */
 
defined('_JEXEC') or die;


class PmapiController extends JController
{

    public function display()
    {
        $mustLogout = self::_login();
        parent::display();
        if ($mustLogout) self::_logout();
    }


    public function logout()
    {
        self::_logout();
        $this->setRedirect(UriHelper::mkHtmlURL());
    }   
 
     
    /**
     * Use basic authentication login if current user is not already logged
     * Use credential stored in HTTP headers and authenticated the user using Joomla standard authentication
     * 
     * @return true if logout is needed before closing connection, false if logout not needed.
     */
    private static function _login()
    {
        $mustLogout = false;
        if (JComponentHelper::getParams('com_pmapi')->get('http_auth',1,'BOOLEAN')){
            $app = JFactory::getApplication();
            $jinput= $app->input;
                    
            $user = JFactory::getUser();
            
            if ($user->guest)  
            {
                // the user is not logged in: try login using basic http authentication method
                $http_username = $jinput->server->get( 'PHP_AUTH_USER','','USERNAME');
                $http_password = $jinput->server->get( 'PHP_AUTH_PW','');
                //use user and password parameter to override HTTP basic authentication
                $credentials = array(
                    'username' => $jinput->get('user',$http_username,'USERNAME'),
                    'password' => $jinput->get('password',$http_password),   
                );
                
                // Try basic authentication if forced login selected or  user name is present in HTTP header
                if ( $credentials['username']){
                    jimport('joomla.user.authentication');
        
                    $authenticate = JAuthentication::getInstance();
                    $response = $authenticate->authenticate($credentials);
                    
                    if ($response->status == 1) { 
                        $response = $app->login($credentials);
                        $mustLogout = true;
                    } else {
                        header('WWW-Authenticate: Basic realm="pmapi"');
                        throw new Exception("Access Denied", 401);
                    }
                }
            }
        }
         
        return $mustLogout;
    }
    
    
    /**
     * Force logout of current user
     */
    private static function _logout()
    {
        $app = JFactory::getApplication();
        $response = $app->logout();     
    }


}